package cn.fl.insurance.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.insurance.condition.InsTypCfgRQueryCondition;
import cn.fl.insurance.condition.InsTypInfoQueryCondition;
import cn.fl.preloan.condition.InsTypCfgRQuerysCondition;
import cn.fl.preloan.dto.*;
import cn.fl.preloan.enums.PreloanResultCodeEnum;
import cn.fl.preloan.insurance.IInsTypCfgRsService;
import cn.fl.preloan.insurance.IInsTypInfosService;
import com.alibaba.dubbo.config.annotation.Reference;
import cn.fl.commons.result.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.service.IInsTypCfgRService;
import cn.fl.insurance.service.IInsTypInfoService;
import cn.fl.insurance.vo.InsTypCfgRVO;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 险种配置关系表 控制层
 */
@Controller
@RequestMapping("/insurance/insTypCfgR")
public class InsTypCfgRController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InsTypCfgRController.class);

    /**
     * InsTypCfgR 服务层BEAN
     */
    @Autowired
    private IInsTypCfgRService insTypCfgRService;

    /**
     * insTypInfo 服务层BEAN
     */
    @Autowired
    private IInsTypInfoService insTypInfoService;
    @Autowired
    private IInsTypCfgRsService insTypCfgRsService;
    @Autowired
    private IInsTypInfosService insTypInfosService;
    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载InsTypCfgR列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insTypCfgR/insTypCfgRList");
        this.prepare(request, mav);
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载InsTypCfgR Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insTypCfgR/insTypCfgRModify");
        this.prepare(request, mav);
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载InsTypCfgR Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insTypCfgR/insTypCfgRModify");
        this.prepare(request, mav);

        String id = request.getParameter("id");
        GetByIdRequest req = new GetByIdRequest();
        req.setId(Long.valueOf(id));
        ResponseData data = this.insTypCfgRsService.selectInsTypCfgRById(req);
        InsTypCfgRVO insTypCfgRVO = new InsTypCfgRVO();
        BeanUtils.copyProperties(data.getData(), insTypCfgRVO);
        mav.addObject("insTypCfgRVO", insTypCfgRVO);
        //查询项目类型
        List<KeyValueVO> prjTypList=this.insTypCfgRService.getPrjTypList(insTypCfgRVO.getBuOrgCd());
        mav.addObject("prjTypCdList", JSON.toJSONString(prjTypList));

        return mav;
    }

    //加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request, ModelAndView mav) {
        //查询事业部
        List<KeyValueVO> buOrgCdList = this.insTypCfgRService.searchBusinessOrgList();
        mav.addObject("buOrgCdList", JSON.toJSONString(buOrgCdList));

        //查询险种大类
        InsTypInfoQueryCondition qc = new InsTypInfoQueryCondition();
        qc.setTypLvl(0);
        List<KeyValueVO> insTypCdList = this.insTypInfoService.searchInsTypCdList(qc);
        mav.addObject("insTypCdList", JSON.toJSONString(insTypCdList));
    }

    /**
     * 查询项目类型KV
     */
    @RequestMapping(value = "/getPrjTypList.do", method = {RequestMethod.GET})
    @ResponseBody
    public DataResultVO getPrjTypList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "查询成功");
        String buOrgCd = request.getParameter("buOrgCd");
        List<KeyValueVO> list = this.insTypCfgRService.getPrjTypList(buOrgCd);
        System.out.println(buOrgCd+"====>>>" + JSON.toJSONString(list));
        if (CollectionUtils.isNotEmpty(list)) {
            result.setData(JSON.toJSONString(list));
        } else {
            result.setSuccess(0);
        }
        return result;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initInsTypCfgRList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(currentPage)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        InsTypCfgRQuerysCondition qc = new InsTypCfgRQuerysCondition();
        //设置查询条件？
        String insTypId = request.getParameter("insTypId");//险种大类
        String buOrgCd=request.getParameter("buOrgCd");//事业部
        String prjTypCd=request.getParameter("prjTypCd");//项目类型
        if (StringUtils.isNotEmpty(insTypId)) {
            qc.setInsTypId(Long.valueOf(insTypId));
        }
        if(StringUtils.isNotBlank(buOrgCd)){
            qc.setBuOrgCd(buOrgCd);
        }
        if(StringUtils.isNotBlank(prjTypCd)){
            qc.setPrjTypCd(prjTypCd);
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initInsTypCfgRList", "初始化InsTypCfgR列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        List<InsTypCfgRVO> insTypCfgRVOList = new ArrayList<>();
        ResponseData<InsTypCfgRPageResponse> data = insTypCfgRsService.searchListPageByCondition(page.getCurrentPage(), page.getEveryPage(), qc);
        List<InsTypCfgRDTO> insTypCfgRDTOList = data.getData().getInsTypCfgRDTOList();
        for(InsTypCfgRDTO insTypCfgRDTO :insTypCfgRDTOList){
            InsTypCfgRVO ins = new InsTypCfgRVO();
            BeanUtils.copyProperties(insTypCfgRDTO, ins);
            insTypCfgRVOList.add(ins);
        }
        ListPageVO<InsTypCfgRVO> listPage = new ListPageVO<InsTypCfgRVO>(insTypCfgRVOList, data.getData().getTotalCount());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeInsTypCfgRByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeInsTypCfgRByIds", "删除InsTypCfgR数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            DeleteByIdsRequest req = new DeleteByIdsRequest();
            req.setIds(idsList);
            ResponseData data = insTypCfgRsService.deleteByIds(req);
            if(!data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeInsTypCfgRByIds", "删除InsTypCfgR数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeInsTypCfgRByIds", "删除InsTypCfgR数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeInsTypCfgRByIds", "删除InsTypCfgR数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeInsTypCfgRByIds", "删除InsTypCfgR数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getInsTypCfgRById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getInsTypCfgRById", "获取InsTypCfgR数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            GetByIdRequest req = new GetByIdRequest();
            req.setId(Long.valueOf(id));
            ResponseData data = insTypCfgRsService.selectInsTypCfgRById(req);
            InsTypCfgRVO vo =new InsTypCfgRVO();
            BeanUtils.copyProperties(data.getData(), vo);
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getInsTypCfgRById", "获取InsTypCfgR数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getInsTypCfgRById", "获取InsTypCfgR数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getInsTypCfgRById", "获取InsTypCfgR数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getInsTypCfgRById", "获取InsTypCfgR数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addInsTypCfgR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        InsTypCfgRVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForInsTypCfgR(request);//获取参数
            AddInsTypCfgRRequest req = new AddInsTypCfgRRequest();
            InsTypCfgRDTO dto = new InsTypCfgRDTO();
            BeanUtils.copyProperties(entity, dto);
            req.setDto(dto);
            ResponseData data = insTypCfgRsService.addInsTypCfgR(req);
            if(data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())){
                BaseLogUtils.info(logger, "addInsTypCfgR", "新增InsTypCfgR数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }else{
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+"新增险种配置失败。");
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addInsTypCfgR", "新增InsTypCfgR数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addInsTypCfgR", "新增InsTypCfgR数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyInsTypCfgR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        InsTypCfgRVO entity = null;
        try {
            entity = this.getRequestParamForInsTypCfgR(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyInsTypCfgR", "修改InsTypCfgR信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
                return result;
            }
             ModifyInsTypCfgRRequest req = new ModifyInsTypCfgRRequest();
            InsTypCfgRDTO dto = new InsTypCfgRDTO();
            BeanUtils.copyProperties(entity, dto);
            req.setDto(dto);
            ResponseData data = insTypCfgRsService.modifyInsTypCfgR(req);
            if (!data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyInsTypCfgR", "修改InsTypCfgR数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyInsTypCfgR", "修改InsTypCfgR数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyInsTypCfgR", "修改InsTypCfgR数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyInsTypCfgR", "修改InsTypCfgR数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/validate.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object validateIns(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String buOrgCd=request.getParameter("buOrgCd");//事业部
        String prjTypCd=request.getParameter("prjTypCd");//项目类型
        String prjPrdDtlId=request.getParameter("prjPrdDtlId");//项目产品明细ID
        String paySchId=request.getParameter("paySchId");//支付表ID
        String prjPrdId=request.getParameter("prjPrdId");//项目产品ID
        String payTypCd=request.getParameter("payTypCd");//放款类型
        String prjId = request.getParameter("prjId");//项目ID
        InsTypCfgRQueryCondition qc=new InsTypCfgRQueryCondition();
        qc.setBuOrgCd(buOrgCd);
        qc.setPrjTypCd(prjTypCd);
        if(StringUtils.isNotBlank(paySchId)){
            qc.setPaySchId(Long.valueOf(paySchId));
        }
        if(StringUtils.isNotBlank(prjPrdDtlId)) {
            qc.setPrjPrdDtlId(Long.valueOf(prjPrdDtlId));
        }
        if(StringUtils.isNotEmpty(prjPrdId)){
            qc.setPrjPrdId(Long.valueOf(prjPrdId));
        }
        if(StringUtils.isNotEmpty(payTypCd)){
            qc.setPayTypCd(payTypCd);
        }
        if(StringUtils.isNotEmpty(prjId)){
            qc.setPrjId(Long.valueOf(prjId));
        }
        return this.insTypCfgRService.validate(qc);
    }


    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private InsTypCfgRVO getRequestParamForInsTypCfgR(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String insTypId = request.getParameter("insTypId");//保险大类
        String buOrgCd = request.getParameter("buOrgCd");//事业部
        String prjTypCd = request.getParameter("prjTypCd");//项目类型  ***;**;
        String isFstReq = request.getParameter("isFstReq");//首年必须
        String isRenewReq = request.getParameter("isRenewReq");//续保必须

        //验证参数并赋值
        InsTypCfgRVO entity = new InsTypCfgRVO();
        if(StringUtils.isBlank(insTypId)){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "保险险种不能为空.");
        }
        if(StringUtils.isBlank(buOrgCd)){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "事业部不能为空.");
        }
        if(StringUtils.isBlank(prjTypCd)){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "项目类型不能为空.");
        }
        entity.setInsTypId(Long.valueOf(insTypId));
        entity.setBuOrgCd(buOrgCd);
        entity.setPrjTypCd(prjTypCd);
        entity.setIsFstReq(Integer.valueOf(isFstReq));
        entity.setIsRenewReq(Integer.valueOf(isRenewReq));

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        }

        return entity;
    }
}

